package com.huixiaodian.baselibrary.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

public class VersionUtil {

    public static String getAPPName(Context context) {
        try{
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return context.getResources().getString(labelRes);
        }catch (PackageManager.NameNotFoundException exception){
            exception.printStackTrace();
        }
        return null;
    }

    /**
     * 获取APP应用版本名称
     * @param context 上下文信息
     * @return 应用版本名称
     */
    public static String getVersionName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            String versionName = packageInfo.versionName;
            if (versionName != null)
                return versionName;
            else
                return "";
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 判断当前APP版本是否是最新版本
     * @param context 上下文信息
     * @param versionCode  服务器端应用的版本
     * @return 本地是否是最新版本
     */
    public static boolean isLastVersionCode(Context context, int versionCode){
        try{
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode >= versionCode;
        }catch (PackageManager.NameNotFoundException e){
            e.printStackTrace();
        }
        return true;
    }

    public static String getApplicationId(Context context){
        return context.getPackageName();
    }
}
